package com.xiaoyi.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoyi.springboot.entity.SysPermission;
import com.xiaoyi.springboot.entity.SysUser;
import com.xiaoyi.springboot.mapper.SysPermissionMapper;
import com.xiaoyi.springboot.mapper.SysUserMapper;
import com.xiaoyi.springboot.mapper.SysUserRoleMapper;
import com.xiaoyi.springboot.service.SysUserService;
import com.xiaoyi.springboot.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xiaoyi
 * @since 2021-03-18
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Set<String> getUserRolesSet(String username) {
        // 查询用户拥有的角色集合
        List<String> roles = sysUserRoleMapper.getRoleByUserName(username);
        return new HashSet<>(roles);
    }

    @Override
    public Set<String> getUserPermissionsSet(String username) {
        Set<String> permissionSet = new HashSet<>();
        List<SysPermission> permissionList = sysPermissionMapper.queryByUser(username);
        for (SysPermission po : permissionList) {
//			// TODO URL规则有问题？
//			if (oConvertUtils.isNotEmpty(po.getUrl())) {
//				permissionSet.add(po.getUrl());
//			}
            if (com.xiaoyi.springboot.util.StringUtils.isNotEmpty(po.getPerms())) {
                permissionSet.add(po.getPerms());
            }
        }
        return permissionSet;
    }

    @Override
    public SysUser getUserByName(String username) {
        if (StringUtils.isEmpty(username)){
            return null;
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        QueryWrapper<SysUser> username1 = queryWrapper.eq("username", username);

        List<SysUser> sysUsers = userMapper.selectList(queryWrapper);
        if(Objects.isNull(sysUsers)|| sysUsers.isEmpty()){
            return null;
        }
        return sysUsers.get(0);
    }


    @Override
    public void addUser(SysUser user) {
        this.save(user);
    }
}
